There's a bit of boilerplate code to get the JBoss EJB3 Embeddable Container initialized before we can look up our session bean. For now we'll just use this code so we won't describe it in any detail here.
By the way, I recommend you cut and past this code rather than type it.
JBossUtil.java
packageutil;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.OutputStream;importjava.io.PrintStream;importjava.util.logging.Logger;importjavax.naming.InitialContext;importjavax.naming.NamingException;importorg.jboss.ejb3.embedded.EJB3StandaloneBootstrap;/**
* This class was originally necessary when using the ALPHA 5 version of the
* embeddable container. With the alpha 9 release, initialization is quite
* simple, you need just 2 lines to initialize your JBoss Embeddable EJB3
* Container Environment. Unfortunately, the one that is available for download
* uses System.out.println() in a few places, so this simple utility hides that
* output and also provides a simple lookup mechanism.
*/publicclass JBossUtil {privatestaticPrintStream originalOut;privatestaticPrintStream originalErr;privatestaticOutputStream testOutputStream;privatestaticPrintStream testOuputPrintStream;staticboolean initialized;staticInitialContext ctx;private JBossUtil(){// I'm a utility class, do not instantiate me}/**
* JBoss EJB3 Embeddable Container uses System.out. Redirect that output to
* keep the console output clean.
*/privatestaticvoid redirectStreams(){// configure the console to get rid of hard-coded System.out's in// the JBoss libraries
testOutputStream = newByteArrayOutputStream(2048);
testOuputPrintStream = newPrintStream(testOutputStream);
originalOut = System.out;
originalErr = System.err;System.setOut(testOuputPrintStream);System.setErr(testOuputPrintStream);}/**
* Restore the System.out and System.err streams to their original state.
* Close the temporary stream created for the purpose of redirecting I/O
* while the initializing is going on.
*/privatestaticvoid restoreStreams(){System.setOut(originalOut);System.setErr(originalErr);
testOuputPrintStream.close();try{
testOutputStream.close();}catch(IOException e){Logger.getLogger(JBossUtil.class.getName()).info("Unable to close testoutstream");}}/**
* This method starts and initializes the embeddable container. We do not
* offer a method to properly clean up the container since this is really
* meant for testing only.
*
* This method may freely be called as often as you'd like since it lazily
* initializes the container only once.
*/publicstaticvoid startDeployer(){if(!initialized){
redirectStreams();
EJB3StandaloneBootstrap.boot(null);
EJB3StandaloneBootstrap.scanClasspath();
initialized = true;
restoreStreams();}}/**
* This is for symmetry. Given how we are using this class, there's little
* need to actually shutdown the container since we run a quick application
* and then stop the JVM.
*/publicstaticvoid shutdownDeployer(){
EJB3StandaloneBootstrap.shutdown();}privatestaticInitialContext getContext(){/**
* We only keep one context around, so lazily initialize it
*/if(ctx == null){try{
ctx = newInitialContext();}catch(NamingException e){thrownewRuntimeException("Unable to get initial context", e);}}return ctx;}/**
* The lookup method on InitialContext returns Object. This simple wrapper
* asks first for the expected type and the for the name to find. It gets
* the name out of JNDI and performs a simple type-check. It then casts to
* the type provided as the first parameter.
*
* This isn't strictly correct since the cast uses the expression (T), where
* T is the generic parameter and the type is erased at run-time. However,
* since we first perform a type check, we know this cast is safe. The -at-
* SuppressWarnings lets the Java Compiler know that we think we know what
* we are doing.
*
* @param <T>
* Type type provided as the first parameter
* @param clazz
* The type to cast to upon return
* @param name
* The name to find in Jndi, e.g. XxxDao/local or, XxxDao/Remote
* @return Something out of Jndi cast to the type provided as the first
* parameter.
*/
@SuppressWarnings("unchecked")publicstatic<T> T lookup(Class<T> clazz, String name){finalInitialContext ctx = getContext();/**
* Perform the lookup, verify that it is type-compatible with clazz and
* cast the return type (using the erased type because that's all we
* have) so the client does not need to perform the cast.
*/try{finalObject object = ctx.lookup(name);if(clazz.isAssignableFrom(object.getClass())){return(T) object;}else{thrownewRuntimeException(String.format("Class found: %s cannot be assigned to type: %s",
object.getClass(), clazz));}}catch(NamingException e){thrownewRuntimeException(String.format("Unable to find ejb for %s", clazz.getName()), e);}}}
EqualsUtil.java
packageutil;/**
* We typically need to compare two object and also perform null checking. This
* class provides a simple wrapper to accomplish doing so.
*/publicclass EqualsUtil {private EqualsUtil(){// I'm a utility class, do not instantiate me}publicstaticboolean equals(finalObject lhs, finalObject rhs){return lhs == null&& rhs == null
|| (lhs != null&& rhs != null&& lhs.equals(rhs));}}
To create this file,
Select your src directory
Right-click and select New::Class
For Class Name enter JBossUtil
For Package enter util
Click Finish
Type or copy the code from above into the new file then save it by pressing ctrl-s
Using JUnit
Now we need to enter basic system setup and then execute a test. The following unit test performs basic setup and initialization, looks up a session bean and sends it a message.
To create this test:
Select your test source folder
Right-click, select New:Class
Enter HelloWorldServiceImplTest for the name
Enter ervice.impl for the package
Click Finish
Copy the text below into the file (replacing the entire contents)
Save the file
packageservice.impl;importorg.junit.Before;importorg.junit.BeforeClass;importorg.junit.Test;importservice.HelloWorldService;importutil.JBossUtil;publicclass HelloWorldServiceImplTest {private HelloWorldService service;
@BeforeClass
publicstaticvoid startDeployer(){// Note, we could stop the deployer when we are done but we do not since// the JVM will shut down and stop the deployer for us.
JBossUtil.startDeployer();}
@Before
publicvoid lookupService(){
service = JBossUtil.lookup(HelloWorldService.class,
"HelloWorldServiceImpl/local");}
@Test
publicvoid sayHello(){
service.sayHelloTo("Brett");}}
Execute your "Unit Test"
Run this JUnit "test" and make sure it runs successfully. (Right-click on the class, select Run As:JUnit Test.
You will see the following output:
Hello to Brett
Note that this example produces output to the console. This example service is not really very testable. How might you "fix" this?
Nice
Congratulations, you've created your first EJB3 Session bean and executed it.
By the way, I recommend you cut and past this code rather than type it.
JBossUtil.java
EqualsUtil.java
To create this file,
Using JUnit
Now we need to enter basic system setup and then execute a test. The following unit test performs basic setup and initialization, looks up a session bean and sends it a message.To create this test:
Execute your "Unit Test"
Run this JUnit "test" and make sure it runs successfully. (Right-click on the class, select Run As:JUnit Test.You will see the following output:
Note that this example produces output to the console. This example service is not really very testable. How might you "fix" this?
Nice
Congratulations, you've created your first EJB3 Session bean and executed it.